<template>
	<vxe-modal id='deptMaintainAddModal' v-bind='modalConfig' @close='closeModal'>
		<template v-slot:title>
			{{ modalConfig['title'] }}
		</template>
		<n-scrollbar trigger='hover'>
			<n-form ref='formRef' v-bind='formConfig'
					:model='formData' :rules='formRules'>
				<n-grid :x-gap='24' :cols='1'>
					<n-form-item-gi span='24' label='上级部门编码' path='parentDeptCode'>
						<n-input v-model:value='formData.parentDeptCode'
								 type='text' placeholder='请输入上级部门编码'
								 disabled/>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='部门编码' path='deptCode'>
						<n-tooltip trigger='click'>
							<template v-slot:trigger>
								<n-input v-model:value='formData.deptCode'
										 type='text' placeholder='请输入部门编码'
										 clearable/>
							</template>
							格式:A001 B001 C001,以顺序字母为开头,以顺序数字为结尾
						</n-tooltip>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='部门简称' path='deptAbbName'>
						<n-input v-model:value='formData.deptAbbName'
								 type='text' placeholder='请输入部门简称'
								 clearable/>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='部门全称' path='deptName'>
						<n-input v-model:value='formData.deptName'
								 type='text' placeholder='请输入部门全称'
								 clearable/>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='部门电话' path='deptPhone'>
						<n-input v-model:value='formData.deptPhone'
								 type='text' placeholder='请输入部门电话'
								 clearable/>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='部门地址' path='deptAddress'>
						<n-input v-model:value='formData.deptAddress'
								 type='text' placeholder='请输入部门地址'
								 clearable/>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='是否禁用' path='disabled'>
						<n-switch v-model:value='formData.disabled as boolean'
								  :checked-value='true' :unchecked-value='false'>
							<template v-slot:checked>是</template>
							<template v-slot:unchecked>否</template>
						</n-switch>
					</n-form-item-gi>
					<n-form-item-gi span='24' label='排序' path='sort'>
						<n-input-number v-model:value='formData.sort'
										style='width:100%;' min='0' clearable/>
					</n-form-item-gi>
					<n-form-item-gi span='24'>
						<n-flex justify='center' style='width:100%;'>
							<n-button type='primary' @click='submitEvent'>
								提交
							</n-button>
							<n-button type='info' @click='resetEvent'>
								重置
							</n-button>
						</n-flex>
					</n-form-item-gi>
				</n-grid>
			</n-form>
		</n-scrollbar>
	</vxe-modal>
</template>
<script lang='ts' setup>
import { onMounted, reactive, ref } from 'vue';
// axios
import axios from '@/config/axios/index.ts';
// 模态框和打印组件
import { VxeUI, VxeModal } from '@/config/vxe/index.ts';
import type { Dict } from '#/Dictionary.d.ts';
import { VxeModalProps } from 'vxe-table';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { FormInst, FormProps, FormRules, FormValidationError } from 'naive-ui';
import type {
	DeptMaintainProps, DeptMaintainInfoProps
} from '#/src/components/page/systemManager/deptMaintain/DeptMaintainProps.d.ts';
// 接收的参数
const props = defineProps({
	reLoad : {
		type    : Function,
		require : true,
		default : null
	}
});
// 预置的字典变量
const dict = reactive<Dict>({});
// 模态框的配置
const modalConfig = reactive<VxeModalProps>({
	modelValue : false,
	title      : '',
	width      : '',
	height     : '',
	showClose  : true,
	resize     : true
});
// 表单配置
const formConfig = reactive<FormProps>({
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	size                 : 'large',
	requireMarkPlacement : 'right-hanging'
});
// 表单绑定数据
const formData = reactive<DeptMaintainProps>({
	mode           : null,
	tenantCode     : null,
	parentDeptCode : null,
	deptCode       : null,
	deptAbbName    : null,
	deptName       : null,
	deptType       : null,
	deptPhone      : null,
	deptAddress    : null,
	disabled       : null,
	sort           : null
});
// 表单校验规则
const formRules = reactive<FormRules>({
	parentDeptCode : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '上级部门编码是必须的'
	},
	deptCode       : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入部门编码'
	},
	deptAbbName    : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入部门简称'
	},
	deptName       : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入部门全称'
	},
	sort           : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '请输入序号'
	}
});
const formRef = ref<FormInst>();
onMounted(() => {
});
const showModal = async (mode: 'subordinate' | 'brother', rowData: DeptMaintainInfoProps) => {
	await clearFormData();
	let title = '';
	switch (mode) {
		case 'subordinate':
			title = '新增子级部门';
			// 子级节点的上级节点是当前节点本身
			formData.parentDeptCode = rowData.deptCode;
			break;
		case 'brother':
			title = '新增同级部门';
			// 同级节点的上级节点是当前节点的上级节点
			formData.parentDeptCode = rowData.parentDeptCode;
			break;
	}
	// 当前选中的部门数据
	formData.mode = mode;
	formData.tenantCode = sessionStorage.getItem('loginTenantCode');
	Object.assign(modalConfig, {
		modelValue : true,
		height     : '500',
		width      : '700',
		title      : title,
		showClose  : true
	});
};
const closeModal = async () => {
	await clearFormData();
	modalConfig.modelValue = false;
};
const resetEvent = async () => {
	// 清理表单数据
	Object.assign(formData, {
		parentDeptCode : null,
		deptCode       : null,
		deptName       : null,
		deptAbbName    : null,
		deptPhone      : null,
		deptAddress    : null,
		disabled       : false,
		sort           : null
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
const clearFormData = async () => {
	// 清理表单数据
	Object.assign(formData, {
		mode           : null,
		tenantCode     : null,
		parentDeptCode : null,
		deptCode       : null,
		deptName       : null,
		deptAbbName    : null,
		deptType       : null,
		deptPhone      : null,
		deptAddress    : null,
		disabled       : false,
		sort           : null
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
const submitEvent = async () => {
	// 校验菜单
	formRef.value?.validate((errors?: Array<FormValidationError>): void => {
		if (errors) {
			VxeUI.modal.message({ content : '请先完善填写的内容!', status : 'warning', id : 'validateMessage' });
		} else {
			// 提交数据
			axios<any, JsonResultProps<any>, any>({
				method : 'POST',
				url    : '/department/add',
				data   : formData
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					props.reLoad(null);
					closeModal();
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
// 导出方法
defineExpose({ showModal });
</script>